package com.xmlt.core.template.tags;

import java.util.ArrayList;
import java.util.List;

import javax.xml.xpath.XPathExpressionException;


import ognl.OgnlException;

import org.w3c.dom.Element;

import com.xmlt.core.template.TemplateException;
import com.xmlt.core.template.TemplateSection;
import com.xmlt.core.template.Utils;
import com.xmlt.core.template.expression.ExpressionFactory;
import com.xmlt.core.template.instance.AbstractInstance;


public class IfTag extends TemplateSectionElement {
	private TemplateSection conditionSection;
	private TemplateSection ifSection;
	private TemplateSection elseSection;
	public IfTag(Element tag) throws TemplateException {
		try {
			Element ifBody = (Element) Utils.evaluateXPath(tag, "ifbody").item(0);
			if (ifBody != null)
				ifSection = new TemplateSection("if", ifBody);
			Element elseBody = (Element) Utils.evaluateXPath(tag, "elsebody").item(0);
			if (elseBody != null)
				elseSection = new TemplateSection("else", elseBody);
		} catch (XPathExpressionException e) {
			throw new TemplateException(e);
		}
	}
	
	public String toString() {
		return "if tag";
	}

	@Override
	public void setParameter(String name, Element el) throws TemplateException {
		if (!"condition".equals(name))
			super.setParameter(name, el);
		else {
			conditionSection = new TemplateSection("condition", el);
		}
	}

	@Override
	public List<TemplateSectionElement> generateTags(AbstractInstance instance) throws OgnlException {
		List<TemplateSectionElement> l = new ArrayList<TemplateSectionElement>();
		if (isConditionTrue(instance)) {
			for (TemplateSectionElement tse: ifSection.getTags()) {
				l.addAll(tse.generateTags(instance));
			}
		} else if (elseSection != null) {
			for (TemplateSectionElement tse: elseSection.getTags()) {
				l.addAll(tse.generateTags(instance));
			}
		}
		return l;
	}
	
	private boolean isConditionTrue(AbstractInstance instance) throws OgnlException {
		String condition = conditionSection.generate(instance);
		return (Boolean) ExpressionFactory.getExpression(condition).evaluate(instance);
	}

}
